﻿using Acr.UserDialogs;
using RaceHFTools.BluetoothLE.Bean;
using RaceHFTools.BluetoothLE.Bean.Module;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace RaceHFTools.Pages
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class UpgradePage : ContentPage
    {
        private readonly Bean bean;

        public UpgradePage(Bean bean)
        {
            InitializeComponent();

            this.bean = bean;
        }

        void CheckBox_Channel_CheckedChanged(object sender, CheckedChangedEventArgs e)
        {
            if (e.Value == false)
                return;

            CheckBox cbx = sender as CheckBox;
            CheckBox[] cbxs = new CheckBox[] { cbxChannelTest, cbxChannelDevelop, cbxChannelRelease };
            foreach (CheckBox c in cbxs)
            {
                if (c != cbx)
                    c.IsChecked = false;
            }
        }

        void Button_UpgradeFirmware_Clicked(object sender, EventArgs e)
        {
            UpgradeFirmware();
        }

        void Button_UpgradeBootloader_Clicked(object sender, EventArgs e)
        {
            UpgradeBootloader();
        }

        void Button_UpgradeAgps_Clicked(object sender, EventArgs e)
        {
            DisplayAlert("升级APGS", "功能暂未开放，敬请期待", "确定");
        }

        void Button_UpgradeGnss_Clicked(object sender, EventArgs e)
        {
            DisplayAlert("升级GNSS", "功能暂未开放，敬请期待", "确定");
        }

        async void Button_PowerOff_Clicked(object sender, EventArgs e)
        {
            await bean.Tweak.SetDevicePower(TweakDevicePowerMode.PowerOff);
        }

        void UpgradeFirmware()
        {
            Task.Run(async () =>
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                using var progress = UserDialogs.Instance.Progress("固件准备中", cts.Cancel, "[取消]");

                void show_process(string process, int percent)
                {
                    progress.Title = process;
                    progress.PercentComplete = percent;
                }

                Utils.Url.URL_CHANNEL channel;
                if (cbxChannelDevelop.IsChecked)
                    channel = Utils.Url.URL_CHANNEL.DEVELOP;
                else if (cbxChannelRelease.IsChecked)
                    channel = Utils.Url.URL_CHANNEL.RELEASE;
                else
                    channel = Utils.Url.URL_CHANNEL.TEST;

                if (File.Exists(Utils.File.Firmware))
                    File.Delete(Utils.File.Firmware);

                //string url = @"https://manage.racehf.com/bean/firmware/test/ota.bin?id=000000600000000010c046d840200538";
                string url = Utils.Url.GetOtaBinUrl(DFU_TYPE.FIRMWARE, channel, bean.Id);
                byte[] data = await Utils.Net.Download(url);
                if (data != null)
                    File.WriteAllBytes(Utils.File.Firmware, data);

                if (File.Exists(Utils.File.Firmware))
                {
                    bool success = await bean.Upgrade.Run(DFU_TYPE.FIRMWARE, File.ReadAllBytes(Utils.File.Firmware), show_process, cts.Token);
                    UserDialogs.Instance.Toast(success ? "固件升级完成" : "固件升级失败");
                }
                else
                {
                    UserDialogs.Instance.Toast("没有固件文件");
                }
            });
        }

        void UpgradeBootloader()
        {
            Task.Run(async () =>
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                using var progress = UserDialogs.Instance.Progress("引导准备中", cts.Cancel, "[取消]");

                void show_process(string process, int percent)
                {
                    progress.Title = process;
                    progress.PercentComplete = percent;
                }

                Utils.Url.URL_CHANNEL channel;
                if (cbxChannelDevelop.IsChecked)
                    channel = Utils.Url.URL_CHANNEL.DEVELOP;
                else if (cbxChannelRelease.IsChecked)
                    channel = Utils.Url.URL_CHANNEL.RELEASE;
                else
                    channel = Utils.Url.URL_CHANNEL.TEST;

                if (File.Exists(Utils.File.Bootloader))
                    File.Delete(Utils.File.Bootloader);

                //string url = @"https://manage.racehf.com/bean/bootloader/test/ota.bin?id=000000600000000010c046d840200538";
                string url = Utils.Url.GetOtaBinUrl(DFU_TYPE.BOOTLOADER, channel, bean.Id);
                byte[] data = await Utils.Net.Download(url);
                if (data != null)
                    File.WriteAllBytes(Utils.File.Bootloader, data);

                if (File.Exists(Utils.File.Bootloader))
                {
                    bool success = await bean.Upgrade.Run(DFU_TYPE.BOOTLOADER, File.ReadAllBytes(Utils.File.Bootloader), show_process, cts.Token);
                    UserDialogs.Instance.Toast(success ? "引导升级完成" : "引导升级失败");
                }
                else
                {
                    UserDialogs.Instance.Toast("没有引导文件");
                }
            });
        }
    }
}